10. RegEx

RegEx

ND079 C1 L4 A10 RegEx

Regular expressions (often abbreviated as RegEx) are used to match or find strings based on a specialized syntax.

The regEx package in Java contains three classes to support these operations

  • Pattern
  • Matcher
  • PatternSyntaxException.

To use RegEx in Java, we have to do two main theings:

  1. Create a Pattern based on a specialized syntax
  2. Use the Matcher to determine if the pattern exists in the String provided

RegEx Syntax

ND079 C1 L4 A11 RegEx Demo

Helpful RegEx Resources

As a Java developer, do you need to thoroughly learn and memorize RegEx syntax? Not necessarily. Unless you're using it very heavily, it will probably suffice to look up the expression you need when you need it. Along those lines, here are some handy resources that you may want to bookmark for later reference:

  • For use of the RegEx class in Java, see the official Java docs on regular expression syntax.
  • For coming up with the regular expression itself, try playing with RegExr.com. You can enter some text and then try out different expressions; when there is a match, the text will be highlighted. The page also has a handy cheatsheet for commonly needed RegEx characters.

Syntax Example

Let's look at the example from the video. First, we start by defining a String for a valid email address using a regular expression:

String emailRegex = "^(.+)@(.+).(.+)$"

Next we use Pattern, which provides a compiled instance of a String regular expression:

Pattern pattern = Pattern.compile(emailRegex)

Finally, we use Matcher, which contains all of the state data for matching a character sequence against the Pattern:

Matcher matcher = pattern.matcher("jeff@example.com")

Select the correct regular expression string to enforce a valid email address, such as:

jeff@example.com

If you like, you can try out the patterns on RegExr.com.

SOLUTION: "^(.+)@(.+).(.+)$"